package com.atguigu.day03;

import com.atguigu.bean.Event;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink08_Transform_FlatMap {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //TODO 3.使用FlatMap实现，如果输入的数据是Songsong，只打印用户名；如果输入的数据是Bingbing，既打印用户名又打印URL
        SingleOutputStreamOperator<String> flatMap = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                //为了方便处理，将读进来的String类型的数据转为Event
                String[] split = value.split(",");
                Event event = new Event(split[0], split[1], Long.parseLong(split[2]));

                if ("songsong".equals(event.user)) {
                    out.collect(event.user);
                } else if ("bingbing".equals(event.user)) {
                    out.collect(event.user);
                    out.collect(event.url);
                }
            }
        });

        flatMap.print();


        env.execute();


    }
}
